﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using System.Text;

using DotNetOpenAuth.ApplicationBlock;
using DotNetOpenAuth.OAuth.Messages;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;
using DotNetOpenAuth.OpenId.RelyingParty;

using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OAuth.ChannelElements;
using DotNetOpenAuth.OpenId.Extensions.OAuth;

using System.Diagnostics;
using System.IO;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using System.Xml;
using OpenIdRelyingPartyWebForms;

namespace YahooSamples.login
{
    public partial class Default : System.Web.UI.Page
    {
        private const string YahooOPIdentifier = "yahoo.com";
        private static readonly OpenIdRelyingParty relyingParty = new OpenIdRelyingParty();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Params["action"] == "login")
            {
                this.GetYahooRequest().RedirectToProvider();
            }
            else if (Request.Params["action"] == "logout")
            {
                State.UserGUID = null;
                State.YahooAccessToken = null;
                State.FriendlyLoginName = null;
                Response.Redirect("~/login/Default.aspx");
            }

            if (!string.IsNullOrEmpty(State.YahooAccessToken))
            {
                Response.Redirect("~/login/Member.aspx");
            }

            IAuthenticationResponse authResponse = relyingParty.GetResponse();
            if (authResponse != null)
            {
                switch (authResponse.Status)
                {
                    case AuthenticationStatus.Authenticated:
                        txt1.Text += "Authentication Success\n";

                        State.FetchResponse = authResponse.GetExtension<FetchResponse>();

                        var positiveAuthorization = authResponse.GetExtension<AuthorizationApprovedResponse>();

                        AuthorizedTokenResponse accessToken = Global.YahooWebConsumer.ProcessUserAuthorization(authResponse);
                        if (accessToken != null)
                        {
                            txt1.Text += "Access token: " + accessToken.AccessToken + "\n";
                            State.YahooAccessToken = accessToken.AccessToken;

                            Response.Redirect("~/login/Member.aspx");
                        }
                        else
                        {
                            txt1.Text += "Authorization Failed\n";
                        }
                        txt1.Text += "Email: \n" + State.FetchResponse.GetAttributeValue("http://axschema.org/contact/email");
                        break;
                    case AuthenticationStatus.Canceled:
                    case AuthenticationStatus.Failed:
                    default:
                        txt1.Text += "Authentication Failed\n";
                        break;
                }
            }
        }


        private IAuthenticationRequest GetYahooRequest()
        {
            var b = new UriBuilder(Request.Url) { Query = "" };
            IAuthenticationRequest authReq = relyingParty.CreateRequest(YahooOPIdentifier, b.Uri, b.Uri);

            // Prepare the OAuth extension
            Global.YahooWebConsumer.AttachAuthorizationRequest(authReq, "");

            // We also want the user's email address
            var fetch = new FetchRequest();
            fetch.Attributes.AddRequired("http://axschema.org/contact/email");
            fetch.Attributes.AddRequired("http://axschema.org/namePerson");
            fetch.Attributes.AddRequired("http://axschema.org/person/gender");
            fetch.Attributes.AddRequired("http://axschema.org/media/image/default");
            fetch.Attributes.AddRequired("http://axschema.org/pref/language");
            authReq.AddExtension(fetch);

            return authReq;
        }


    }

}